import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/date_picker.dart';
import 'package:flutter_cupertino_date_picker/date_picker_i18n.dart';
import 'package:flutter_cupertino_date_picker/date_picker_theme.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wanchong/api/user.dart';
import 'package:wanchong/bean/success_entity.dart';
import 'package:wanchong/bean/user_info_entity.dart';
import 'package:wanchong/conf.dart';
import 'package:wanchong/utils/event_bus.dart';
import 'package:wanchong/utils/upload.dart';
import 'package:wanchong/widget/app_bar.dart';
import 'package:wanchong/path.dart';

import 'nick.dart';

//import 'package:flutter_cupertino_data_picker/flutter_cupertino_data_picker.dart';
class UserInfo extends StatefulWidget {
  UserInfoDataUser user;
  UserInfo({Key key, this.user});
  @override
  _UserInfoState createState() => _UserInfoState();
}

class _UserInfoState extends State<UserInfo> {

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      resizeToAvoidBottomPadding: false,
      appBar: MyAppBar(
          child: Align(
        //alignment: Alignment.center,
        child: Container(
          padding: EdgeInsets.only(left: 10.0, right: 10.0),
          child: Stack(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                },
                child: new Align(
                  alignment: FractionalOffset.centerLeft,
                  child: Container(
                    padding: EdgeInsets.only(right: 15.0),
                    color: Colors.transparent,
                    height: double.infinity,
                    child: Image.asset("assets/login/top_return_icon.png"),
                  ),
                ),
              ),
              new Align(
                alignment: FractionalOffset.center,
                child: new Text(
                  '个人中心',
                  style: new TextStyle(
                    color: Color(0xFF3C4450),
                    fontSize: 15.0,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ],
          ),
        ),
      )),
      body: Container(
        child: Container(
          child: Column(
            children: <Widget>[
              GestureDetector(
                onTap: () {
                  _getImage();
                },
                child: Container(
                  height: 80.0,
                  padding: EdgeInsets.only(left: 15.0, right: 10.0),
                  color: Color(0xFFFFFFFF),
                  margin: EdgeInsets.only(top: 15.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        child: Text("头像",
                            style: new TextStyle(
                              color: Color(0xFF3C4450),
                              fontSize: 14.0,
                              decoration: TextDecoration.none,
                            ),
                            textAlign: TextAlign.left),
                      ),
                      Row(
                        children: <Widget>[
                          CircleAvatar(
                            backgroundImage:
                                CachedNetworkImageProvider(widget.user.head),
                            radius: 30.0,
                          ),
                          Icon(
                            Icons.chevron_right,
                            color: Color(0xFFB4BEC6),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
              GestureDetector(
                  onTap: () {
                    _editNick();
                  },
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: 60.0,
                        color: Color(0xFFFFFFFF),
                        padding: EdgeInsets.only(left: 15.0, right: 10.0),
                        margin: EdgeInsets.only(top: 15.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              child: Text(
                                "昵称",
                                style: new TextStyle(
                                    color: Color(0xFF3C4450),
                                    fontSize: 14.0,
                                    decoration: TextDecoration.none),
                              ),
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  widget.user.nick,
                                  style: new TextStyle(
                                      color: Color(0xFFB4BEC6), fontSize: 14.0),
                                ),
                                Icon(
                                  Icons.chevron_right,
                                  color: Color(0xFFB4BEC6),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      Container(
                        height: 1,
                        color: Color(0x5eDBDBDB),
                        margin: EdgeInsets.only(left: 15.0),
                      )
                    ],
                  )),
              GestureDetector(
                onTap: (){
                  _showSexPicker();
                },
                  child: Column(
                children: <Widget>[
                  Container(
                    height: 60.0,
                    padding: EdgeInsets.only(left: 15.0, right: 10.0),
                    color: Color(0xFFFFFFFF),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Container(
                          child: Text(
                            "性别",
                            style: new TextStyle(
                                color: Color(0xFF3C4450), fontSize: 14.0),
                          ),
                        ),
                        Row(
                          children: <Widget>[
                            Text(
                              widget.user.sex == "1" ? '男' : '女',
                              style: new TextStyle(
                                  color: Color(0xFFB4BEC6), fontSize: 14.0),
                            ),
                            Icon(
                              Icons.chevron_right,
                              color: Color(0xFFB4BEC6),
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  Container(
                    height: 1,
                    color: Color(0x5eDBDBDB),
                    margin: EdgeInsets.only(left: 15.0),
                  )
                ],
              )),
              GestureDetector(
                  onTap: () {
                    _showDatePicker();
                  },
                  child: Column(
                    children: <Widget>[
                      Container(
                        height: 60.0,
                        padding: EdgeInsets.only(left: 15.0, right: 10.0),
                        color: Color(0xFFFFFFFF),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                              child: Text(
                                "生日",
                                style: new TextStyle(
                                    color: Color(0xFF3C4450), fontSize: 14.0),
                              ),
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  widget.user.birthday==0?"未设置":widget.user.birthday.toString(),
                                  style: new TextStyle(
                                      color: Color(0xFFB4BEC6), fontSize: 14.0),
                                ),
                                Icon(
                                  Icons.chevron_right,
                                  color: Color(0xFFB4BEC6),
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                      Container(
                        height: 1,
                        color: Color(0x5eDBDBDB),
                        margin: EdgeInsets.only(left: 15.0),
                      )
                    ],
                  )),
              GestureDetector(
                child: Container(
                  height: 60.0,
                  padding: EdgeInsets.only(left: 15.0, right: 10.0),
                  color: Color(0xFFFFFFFF),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        child: Text(
                          "所在城市",
                          style: new TextStyle(
                              color: Color(0xFF3C4450), fontSize: 14.0),
                        ),
                      ),
                      Row(
                        children: <Widget>[
                          Text(
                            widget.user.city == null ? '未设置' : widget.user.city,
                            style: new TextStyle(
                                color: Color(0xFFB4BEC6), fontSize: 14.0),
                          ),
                          Icon(
                            Icons.chevron_right,
                            color: Color(0xFFB4BEC6),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
                  _addLoc();
                },
                child: Container(
                  height: 60.0,
                  padding: EdgeInsets.only(left: 15.0, right: 10.0),
                  margin: EdgeInsets.only(top: 15.0),
                  color: Color(0xFFFFFFFF),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        child: Text(
                          "收货地址",
                          style: new TextStyle(
                              color: Color(0xFF3C4450), fontSize: 14.0),
                        ),
                      ),
                      Row(
                        children: <Widget>[
                          Text(
                            "未设置",
                            style: new TextStyle(
                                color: Color(0xFFB4BEC6), fontSize: 14.0),
                          ),
                          Icon(
                            Icons.chevron_right,
                            color: Color(0xFFB4BEC6),
                          )
                        ],
                      )
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _addLoc() {
    Navigator.of(context).pushNamed(AddLocPath);
  }

  Future _getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    FileUtils.getInstance().uploadFile(image, (data) {
      Map<String, dynamic> dataMap = json.decode(data);
      if (dataMap["code"] == 200) {
        widget.user.head = dataMap["data"];
        _save(FormData.from({"head": dataMap["data"]}));
      }
    });
  }

  ///保存用户信息
  _save(FormData data) {
    saveUser(data).listen((SuccessEntity data) {
      if (data.code == 200) {
        ///通知主页面更新用户信息
        _updateEvent();
        setState(() {});
      }
    });
  }

  ///通知主页面更新用户信息
  _updateEvent() {
    eventBus.emit(UpdateUser);
  }

  ///修改昵称
  _editNick() async {
    var nick = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => AnimNick()));
    if (widget.user.nick != nick) {
      widget.user.nick = nick;
      _save(FormData.from({"nick": nick}));
    }
  }

  /// Display date picker.
  void _showDatePicker() {
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        // showTitle: _showTitle,
        confirm: Text(
          '确认',
          style: TextStyle(color: Colors.cyan),
        ),
        cancel: Text(
          '取消',
          style: TextStyle(color: Colors.red),
        ),
      ),
      locale: DateTimePickerLocale.zh_cn,
      // minDateTime: DateTime.parse(MIN_DATETIME),
      // maxDateTime: DateTime.parse(MAX_DATETIME),
      // initialDateTime: _dateTime,
      dateFormat: 'yyyy-MM-dd',
      // locale: _locale,
      onConfirm: (dateTime, List<int> index) {
        // var time = dateTime.microsecondsSinceEpoch/1000;
        var time = dateTime.millisecondsSinceEpoch ~/ 1000;
        widget.user.birthday = dateTime.year.toString() +
            "-" +
            dateTime.month.toString() +
            "-" +
            dateTime.day.toString();
        _save(FormData.from({"birthday": time}));
        // print(time);
        // }
        //print();
      },
    );
  }


  ///显示性别
  _showSexPicker() {
    Picker(
        confirmText: "确认",
        cancelText: "取消",
        adapter: PickerDataAdapter<String>(pickerdata: ["男", "女"]),
        changeToFirst: true,
        hideHeader: false,
        onConfirm: (Picker picker, List value) {
          // print(value.toString());
          // print(picker.adapter.text);
          setState(() {
            // sex = (value[0] + 1).toString();
            // _sex = SEXS[value[0]];
            //  complated4 = sex!="" &&
            if (widget.user.sex != (value[0] + 1).toString()) {
              widget.user.sex = (value[0] + 1).toString();

              _save(FormData.from({"sex": (value[0] + 1).toString()}));
            }
          });
        }).show(_scaffoldKey.currentState);
  }
}
